from django.db.models.aggregates import Sum
from duckserver.models import User
from duckserver.models import Studyrecord
import datetime


# 获取用户专注时间分布
'''
{
      day: {
        data: [
          { value: 20, name: "番茄钟" },
          { value: 30, name: "定计划" },
          { value: 25, name: "自习室" }
        ],
        hour: 1,
        minute: 15
      },
      week: {
        data: [
          { value: 80, name: "番茄钟" },
          { value: 60, name: "定计划" },
          { value: 75, name: "自习室" }
        ],
        hour: 3,
        minute: 45
      },
      month: {
        data: [
          { value: 120, name: "番茄钟" },
          { value: 80, name: "定计划" },
          { value: 75, name: "自习室" }
        ],
        hour: 4,
        minute: 35
      }
    }
'''


def getFocusDistribution(userid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)

    now = datetime.datetime.now()

    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute,
                                         seconds=now.second, microseconds=now.microsecond)
    last_week = zeroToday - datetime.timedelta(days=6)
    last_month = zeroToday - datetime.timedelta(days=30)

    all_records = Studyrecord.objects.filter(userid=user)
    day_records = all_records.filter(starttime__gt=zeroToday)
    week_records = all_records.filter(starttime__gt=last_week)
    month_records = all_records.filter(starttime__gt=last_month)

    # type(0:番茄钟,1:长期计划，2:自习室)
    # 日
    data = []
    clock_sum = day_records.filter(type=0).aggregate(
        nums=Sum('runtime'))['nums']

    plan_sum = day_records.filter(type=1).aggregate(
        nums=Sum('runtime'))['nums']

    room_sum = day_records.filter(type=2).aggregate(
        nums=Sum('runtime'))['nums']

    if clock_sum is None:
        clock_sum = 0
    else:
        clock_sum = int(clock_sum)

    if plan_sum is None:
        plan_sum = 0
    else:
        plan_sum = int(clock_sum)

    if room_sum is None:
        room_sum = 0
    else:
        clock_sum = int(clock_sum)

    data.append({'value': clock_sum, 'name': "番茄钟"})
    data.append({'value': plan_sum, 'name': "定计划"})
    data.append({'value': room_sum, 'name': "自习室"})
    total_time = clock_sum + plan_sum + room_sum

    hour = total_time // 60
    minute = total_time % 60

    day_obj = {'data': data, 'hour': hour, 'minute': minute}
    response['day'] = day_obj

    # 周
    data = []
    clock_sum = week_records.filter(type=0).aggregate(
        nums=Sum('runtime'))['nums']

    plan_sum = week_records.filter(type=1).aggregate(
        nums=Sum('runtime'))['nums']

    room_sum = week_records.filter(type=2).aggregate(
        nums=Sum('runtime'))['nums']

    if clock_sum is None:
        clock_sum = 0
    else:
        clock_sum = int(clock_sum)

    if plan_sum is None:
        plan_sum = 0
    else:
        plan_sum = int(clock_sum)

    if room_sum is None:
        room_sum = 0
    else:
        clock_sum = int(clock_sum)

    data.append({'value': clock_sum, 'name': "番茄钟"})
    data.append({'value': plan_sum, 'name': "定计划"})
    data.append({'value': room_sum, 'name': "自习室"})
    total_time = clock_sum + plan_sum + room_sum

    hour = total_time // 60
    minute = total_time % 60

    week_obj = {'data': data, 'hour': hour, 'minute': minute}
    response['week'] = week_obj

    # 月
    data = []
    clock_sum = month_records.filter(type=0).aggregate(
        nums=Sum('runtime'))['nums']

    plan_sum = month_records.filter(type=1).aggregate(
        nums=Sum('runtime'))['nums']

    room_sum = month_records.filter(type=2).aggregate(
        nums=Sum('runtime'))['nums']

    if clock_sum is None:
        clock_sum = 0
    else:
        clock_sum = int(clock_sum)

    if plan_sum is None:
        plan_sum = 0
    else:
        plan_sum = int(clock_sum)

    if room_sum is None:
        room_sum = 0
    else:
        clock_sum = int(clock_sum)

    data.append({'value': clock_sum, 'name': "番茄钟"})
    data.append({'value': plan_sum, 'name': "定计划"})
    data.append({'value': room_sum, 'name': "自习室"})

    total_time = clock_sum + plan_sum + room_sum

    hour = total_time // 60
    minute = total_time % 60

    month_obj = {'data': data, 'hour': hour, 'minute': minute}
    response['month'] = month_obj

    response['ok'] = 1
    return response


'''
{
    "data": [
        [
            "2020-01-21",
            1
        ],
        [
            "2020-01-24",
            1
        ],
        [
            "2020-01-25",
            1
        ],
    ]
}
'''
def getLineChart(userid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)

    now = datetime.datetime.now()
    data = []
    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute,
                                         seconds=now.second, microseconds=now.microsecond)
    zeroToday = zeroToday - datetime.timedelta(days=30)
    zeroTomorrow = zeroToday + datetime.timedelta(days=1)
    allRecord = Studyrecord.objects.filter(userid=user)

    for i in range(0,31):
        day_data=[]
        dayStudyTime = allRecord.filter(starttime__gte=zeroToday).filter(
            starttime__lt=zeroTomorrow).aggregate(nums=Sum('runtime'))['nums']

        if dayStudyTime is None:
            dayStudyTime = 0
        else:
            dayStudyTime = int(dayStudyTime)
        day_data.append(datetime.datetime.strftime(zeroToday, '%m-%d'))
        day_data.append(dayStudyTime)
        data.append(day_data)
        zeroToday = zeroTomorrow
        zeroTomorrow = zeroTomorrow + datetime.timedelta(days=1)
    response['data'] = data
    response['ok'] = 1
    return response


'''
{
    "data": [
        {
            "value": 335,
            "name": "不想学了"
        },
        {
            "value": 310,
            "name": "临时急事"
        },
        {
            "value": 234,
            "name": "手机切屏"
        },
        {
            "value": 135,
            "name": "其他"
        },
        {
            "value": 1548,
            "name": "贪玩"
        }
    ]
}
'''
def getFailReasonChart(userid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)

    now = datetime.datetime.now()
    data = []
    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute,
                                         seconds=now.second, microseconds=now.microsecond)
    # 获取30天前的零点
    zeroToday = zeroToday - datetime.timedelta(days=30)
    failreasonSet = Studyrecord.objects.filter(userid=user).filter(
        starttime__gte=zeroToday).filter(iscompleted=0).values('failreason')

    failreasonList=[]
    failreasonNum=[]
    for reason in failreasonSet:
        if reason['failreason'] in failreasonList:
            failreasonNum[failreasonList.index(reason['failreason'])]+=1
        else:
            failreasonList.append(reason['failreason'])
            failreasonNum.append(1)


    for i in range(0,len(failreasonList)):
        reason_data = {}
        reason_data['value'] = failreasonNum[i]
        reason_data['name'] = failreasonList[i]
        data.append(reason_data)

    response['data'] = data
    response['ok'] = 1
    return response


def getWorkTime(userid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)

    now = datetime.datetime.now()

    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute,
                                         seconds=now.second, microseconds=now.microsecond)
    last_month = zeroToday - datetime.timedelta(days=30)
    all_records = Studyrecord.objects.filter(userid=user)
    month_records = all_records.filter(starttime__gt=last_month)
    data=[]
    record=[0]*24
    allStudyRecord=month_records.filter(type=0)|month_records.filter(type=1)|month_records.filter(type=2)
    for studyrecord in allStudyRecord:
        hour=(int)(studyrecord.starttime.strftime('%H'))
        min=(int)(studyrecord.starttime.strftime('%M'))
        runtime=(int)(studyrecord.runtime)
        left_min=min
        right_min=60-min
        hour_s=(int)((runtime+left_min)//60)
        #print(hour_s)
        min_s=(int)((runtime+left_min)%60)
        #print(min_s)
        if hour_s==0:
                record[hour]+=runtime
        else:
            for j in range(hour_s+1):
                if(j==0):
                    record[hour]+=right_min
                elif(j==hour_s):
                    record[(hour+j)%24]+=min_s
                else:
                    record[(hour+j)%24]+=60
            record[hour]=int(record[hour])
    #print(record)
    for i in range(24):
        data.append({'value':record[i]})
    # for i in range(24):
        
    #     if i<10:
    #         times_i=allStudyRecord.filter(starttime__icontains=' 0'+i+":")
    #     else:
    #         times_i=allStudyRecord.filter(starttime__icontains=' '+i+":")
    #     if len(times_i)!=0:
    #         print(times_i[0].runtime)
    #     # record[i]=times_i.aggregate(
    #     # nums=Sum('runtime'))['nums']
    #     for time in times_i:
    #         starttime=time.starttime
    #         left_min=starttime-buttom_time
    #         left_min=(int) (left_min.seconds//60)
    #         right_min=up_time-starttime
    #         right_min=(int)(right_min.seconds//60)
    #         runtime=time.runtime+left_min
    #         runtime=int(runtime)
    #         hour=runtime//60
    #         min=runtime%60
    #         hour=int(hour)
    #         min=int(min)
    #         if hour==0:
    #             record[i]+=runtime
    #         else:
    #             for j in range(hour):
    #                 if(j==0):
    #                     record[i]+=right_min
    #                 elif(j==hour):
    #                     record[(i+hour)%24]+=min
    #                 else:
    #                     record[(i+j)%24]=60
    #         record[i]=int(record[i])
    response['year']=datetime.datetime.now().year
    response['month']=datetime.datetime.now().month
    response['data']=data
    response['ok']=1
    return response

def getLearningDetail(userid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    all_records = Studyrecord.objects.filter(userid=user)
    now = datetime.datetime.now()

    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute,
                                         seconds=now.second, microseconds=now.microsecond)
    day_records = all_records.filter(starttime__gt=zeroToday)
    # 当天时间
    clock_sum = day_records.filter(type=0).aggregate(
        nums=Sum('runtime'))['nums']

    plan_sum = day_records.filter(type=1).aggregate(
        nums=Sum('runtime'))['nums']

    room_sum = day_records.filter(type=2).aggregate(
        nums=Sum('runtime'))['nums']
    if clock_sum is None:
        clock_sum = 0
    else:
        clock_sum = int(clock_sum)

    if plan_sum is None:
        plan_sum = 0
    else:
        plan_sum = int(clock_sum)

    if room_sum is None:
        room_sum = 0
    else:
        clock_sum = int(clock_sum)
    
    total_time = clock_sum + plan_sum + room_sum

    hour = total_time // 60
    minute = total_time % 60
    response['todayTimes']=len(day_records)
    response['todayHour']=hour
    response['todayMinute']=minute
    response['todayFail']=len(day_records.filter(iscompleted=0))
    #获取所有
    clock_sum = all_records.filter(type=0).aggregate(
        nums=Sum('runtime'))['nums']

    plan_sum = all_records.filter(type=1).aggregate(
        nums=Sum('runtime'))['nums']

    room_sum = all_records.filter(type=2).aggregate(
        nums=Sum('runtime'))['nums']
    if clock_sum is None:
        clock_sum = 0
    else:
        clock_sum = int(clock_sum)

    if plan_sum is None:
        plan_sum = 0
    else:
        plan_sum = int(clock_sum)

    if room_sum is None:
        room_sum = 0
    else:
        clock_sum = int(clock_sum)
    
    total_time = clock_sum + plan_sum + room_sum

    hour = total_time // 60
    minute = total_time % 60
    response['allTimes']=len(all_records)
    response['allHour']=hour
    response['allMinute']=minute
    allaverage=0
    if len(all_records)!=0:
        all_records=all_records.order_by("starttime")
        first=all_records[0]
        firsttime=first.starttime
        deltatime=now-firsttime
        days=deltatime.days
        if days==0:
            allaverage=total_time
        else:
            allaverage=total_time//days
    response['allAverage']=allaverage

    response['ok']=1
    return response
